package com.example.gw_back_end.service.mongodb;

import com.example.gw_back_end.utils.ThreadLocalUtil;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SettingService {

    private final MongoTemplate mongoTemplate;
    public SettingService(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    private static final String SETTING_COLLECTION= "gw_setting";

    // 获取用户设置
    public Object getSetting() {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer)claims.get("id");
        return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), Document.class, SETTING_COLLECTION);
    }

    // 更新用户设置
    public Object updateSetting(Object setting) {
        Map<String,Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer)claims.get("id");
        Document document = new Document("_id", id)
                .append("setting", setting);
        return mongoTemplate.save(document, SETTING_COLLECTION);
    }
}
